﻿<template>
    <div v-cloak class="main">
        <template v-if="isDelete">
            <div class="content">
                <NoTemplateTip :tip="$t('GroupNoticeIsDelete')"></NoTemplateTip>
            </div>
        </template>
        <template v-else>
            <div class="user-info-box">
                <div class="user-inner-box">
                    <img class="avatar-box" v-if="getAvatar()" :src="getAvatar()" alt="" />

                    <div class="info-box">
                        <div class="user-name">{{ noticeInfo.updatedBy }}</div>
                        <div class="opr-box">
                            {{ timer }}
                        </div>
                    </div>
                    <div v-if="noticeInfo.isTop === 1" class="top-box">
                        <div class="top-button">{{ $t('SetTop') }}</div>
                    </div>
                </div>
            </div>
            <div class="content" :style="{ 'max-height': canEdit ? 'calc(100% - 110px)' : 'calc(100% - 50px)' }">
                <div class="content-box" v-html="content"></div>
            </div>
            <div class="button-box">
                <van-button style="width: 100%" class="btn" v-if="canEdit" @click="deleteGroupNotice">
                    {{ $t('Delete') }}
                </van-button>
            </div>

            <!-- <van-button @click="goEdit">编辑</van-button> -->
        </template>
    </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import api from '@/apis/gounp';
import NoTemplateTip from '@/components/NoTemplateTip.vue';
import { isJsonStr, getDateTime, getStore, extractFileName, getFileIconByGroupNotice } from '@/utils/utils';
import avatarImg from '@/assets/avatar.svg';
import { useI18n } from 'vue-i18n';
import { getAppConfig } from '@/utils/getAppConfig';
const { t, locale } = useI18n();
const config = ref<any>({});
const route = useRoute();
const router = useRouter();
const content = ref('');
const groupId = ref<string>('');
const groupAnnouncementId = ref<string>('');
const canEdit = ref(false);
const isDelete = ref(false);
const noticeInfo = ref<any>({
    announcement: '',
    announcementMessage: '',
    avatar: '',
    groupAnnouncementId: 0,
    isTop: 0,
    updatedBy: '',
    updatedDate: '',
    userId: 0,
});

const timer = computed(() => {
    return noticeInfo.value.updatedDate ? getDateTime(Date.parse(noticeInfo.value.updatedDate).toString())[6] : '-';
});

const getAvatar = () => {
    if (noticeInfo.value.avatar) {
        return config.value.avatarUrl + noticeInfo.value.avatar;
    } else {
        avatarImg;
    }
};

const getData = (dataStr: string) => {
    if (!dataStr) return;

    dataStr = dataStr.replace(/<img(.*?)src="(.*?)"(.*?)>/g, (match, p1, p2, p3) => {
        if (p3.includes('alt="file_{')) {
            const fileName = extractFileName(p3);
            if (fileName) {
                return `<img${p1}src="${getFileIconByGroupNotice(fileName)}"${p3}>`;
            }
        }
        if (p2.startsWith('http')) {
            return `<img${p1}src="${p2}"${p3}>`;
        }
        return `<img${p1}src="${config.value.imDomainUrl}${p2}"${p3}>`;
    });
    content.value = dataStr;
    setTimeout(() => {
        let imgList = document.querySelectorAll('img');

        imgList.forEach(item => {
            item.onclick = () => {
                if (item.alt.startsWith('image')) {
                    let { imgObjArr, index }: any = findAllImg(imgList, item);
                    _bridge.callNative('h5DownloadImage', {
                        dataList: JSON.stringify(imgObjArr),
                        index: index,
                    });
                } else if (item.alt.startsWith('file')) {
                    let objStr = item.alt.split('file_')[1]?.replace(/'/, '"');
                    if (isJsonStr(objStr as string)) {
                        let fileObj = JSON.parse(objStr as string);

                        _bridge.callNative('h5DownloadFile', {
                            fileName: fileObj.fileName,
                            filePath: `${config.value.imDomainUrl}${fileObj.url}`,
                            fileSize: fileObj.fileSize,
                        });
                    }
                }
            };
        });
        let attachmentList = document.querySelectorAll('.attachment-box');

        attachmentList.forEach((item: any) => {
            item.onclick = () => {
                const textContent = item.attributes['data-alt'].textContent || '';
                // console.log(textContent.split('file_')[1]);

                let objStr = textContent.split('file_')[1].replaceAll("'", '"');
                // console.log(objStr);

                if (isJsonStr(objStr)) {
                    let fileObj = JSON.parse(objStr);
                    console.log(fileObj);

                    _bridge.callNative('h5DownloadFile', {
                        fileName: fileObj.fileName,
                        filePath: `${config.value.imDomainUrl}${fileObj.url}`,
                        fileSize: fileObj.fileSize,
                    });
                }
            };
        });
    });
};

const findAllImg = (imgList: any, img: any) => {
    if (!imgList) return;
    imgList = Array.from(imgList);
    let images = imgList.filter((i: any) => i.alt.startsWith('image'));
    let index = images.findIndex((i: any) => i.alt === img.alt);
    let imgObjArr: any = [];
    images.forEach((item: any) => {
        let imgObjStr = item.alt.split('_')[1].replaceAll("'", '"');
        if (isJsonStr(imgObjStr)) {
            let imgObj = JSON.parse(imgObjStr);
            let name = imgObj.url.split('%2F').pop();
            imgObjArr.push({
                path: `${config.value.imDomainUrl}${imgObj.url}`,
                name,
            });
        }
    });
    return {
        imgObjArr,
        index,
    };
};

const goEdit = () => {
    _bridge.callNative('hideAppButton');
    router.push({
        name: 'groupNotice',
        query: {
            groupId: route.query.groupId,
            groupAnnouncementId: route.query.groupAnnouncementId || '0',
        },
    });
};

const getNotice = () => {
    if (groupAnnouncementId.value === '0') return;
    api.getGroupAnnouncementDetail(groupId.value, groupAnnouncementId.value).then(res => {
        if (!res || res.code !== 1) return;
        if (!res.data) {
            isDelete.value = true;
            canEdit.value = false;
            _bridge.callNative('hideAppButton');
            return;
        }
        noticeInfo.value = res.data;

        getData(res.data.announcement);
    });
};

const deleteGroupNotice = () => {
    // @ts-ignore
    showConfirmDialog({
        title: t('Prompt'),
        message: t('ConfirmDeleteGroupNotice'),
        cancelButtonText: t('Cancle'),
        confirmButtonText: t('Confirm'),
    })
        .then(async () => {
            const reslut = await api.deleteGroupAnnouncementDetail(groupId.value, groupAnnouncementId.value);
            if (!reslut || reslut.code != 1) return;
            _bridge.callNative('callAppRefreshGroupNoticeList', {
                groupAnnouncementId: groupAnnouncementId.value,
            });
            goBack();
        })
        .catch(() => {});
};

const goBack = () => {
    _bridge.callNative('goBack');
};

const created = async () => {
    await getAppConfig();
    config.value = getStore('mamak-config');
    locale.value = getStore('mamak-lang');

    canEdit.value = (route.query.canEdit || '0') === '1';

    if (canEdit.value) {
        _bridge.callNative('setNavRightBtn', { type: 2, name: 'navi_edit' });
    }
    window.rightBtnClick = goEdit;
    _bridge.callNative('setTitle', { name: t('GroupNotice') });
    groupId.value = route.query.groupId as string;
    groupAnnouncementId.value = (route.query.groupAnnouncementId as string) || '0';
    getNotice();
};
created();
</script>

<style scoped lang="scss">
.main {
    width: 100%;
    height: 100%;
    overflow: hidden;
    text-align: left;
    padding: 10px 0;
    position: relative;
    background: #ecf1f2;

    .user-info-box {
        height: 50px;
        margin-bottom: 10px;
        padding: 0 6px;

        .user-inner-box {
            width: 100%;
            height: 100%;
            border-radius: 4px;
            background: #fff;
            padding: 0 12px;
            display: flex;
            align-items: center;
            .avatar-box {
                width: 39px;
                height: 39px;
                border-radius: 50%;
                margin-right: 10px;
            }

            .info-box {
                .user-name {
                    max-width: 200px;
                    font-size: 16px;
                    color: #000;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .opr-box {
                    font-size: 12px;
                    margin-top: 5px;
                    color: #afafaf;
                }
            }

            .top-box {
                margin-left: auto;
                font-size: 12px;
                color: #fff;

                .top-button {
                    border-radius: 12px;
                    width: 60px;
                    height: 26px;
                    background: #11bf8e;
                    text-align: center;
                    line-height: 26px;
                    cursor: pointer;
                }
            }
        }
    }

    .content {
        padding: 0 6px;
        min-height: 400px;
        max-height: calc(100% - 60px);
        border-radius: 4px;
        word-break: break-all;
        width: 100%;
        margin: 0 auto;
        overflow-x: hidden;
        overflow-y: auto;
    }

    .content-box {
        overflow: hidden;
        background: #fff;
        width: 100%;
        border-radius: 4px;
        padding: 9px;

        :deep(img) {
            max-width: 100%;
        }

        :deep(p) {
            line-height: 24px;
            margin: 0;
        }
    }

    .button-box {
        width: 100%;
        padding: 0 6px;
        height: 45px;
        position: absolute;
        bottom: 10px;

        .btn {
            background: #fff !important;
            width: 100%;
            height: 100%;
            border: none;
            color: #cf3326;
        }
    }
}
</style>

<style lang="scss">
body {
    min-height: unset;

    .attachment-box {
        width: 100%;
        display: flex;
        align-items: center;
        .attachment-name {
            font-size: 12px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        img {
            width: 22px;
        }
    }
}
</style>
